package com.yuke.cloud.service.cmc.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import com.google.common.base.Preconditions;
import com.yuke.cloud.common.core.support.BaseService;
import com.yuke.cloud.common.util.RedisKeyUtil;
import com.yuke.cloud.service.api.cmc.dto.CmsSecKillSkuDto;
import com.yuke.cloud.service.api.opc.dto.UploadFile;
import com.yuke.cloud.service.api.opc.service.OpcFileFeignApi;
import com.yuke.cloud.service.cmc.dao.CmsSecKillSkuMapper;
import com.yuke.cloud.service.cmc.entity.CmsSecKillSku;
import com.yuke.cloud.service.cmc.service.CmsSecKillService;
import com.yuke.cloud.service.cmc.service.CmsSecKillSkuService;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;


/**
 * Created by wg on 2019/05/28.
 */
@Service
@Transactional
public class CmsSecKillSkuServiceImpl extends BaseService<CmsSecKillSku> implements CmsSecKillSkuService {
    @Resource
    private CmsSecKillSkuMapper cmsSecKillSkuMapper;

    @Resource
    private CmsSecKillService cmsSecKillService;
    @Resource
    private OpcFileFeignApi opcFileFeignApi;

    @Resource
    private RedisTemplate<String, Object> redisTemplate;

    @Override
    public int update(CmsSecKillSku cmsSecKillSku) {
        Boolean bUpdate = !cmsSecKillService.isSecKillOn(cmsSecKillSku.getSecKillId());
        //Preconditions.checkState(bUpdate, "秒杀活动正在进行中，无法修改");

        int ret = super.update(cmsSecKillSku);

        // 更新缓存
        CmsSecKillSkuDto cmsSecKillSkuDto = (CmsSecKillSkuDto) redisTemplate.opsForValue().get(RedisKeyUtil.getSecKillSkuKey(String.valueOf(cmsSecKillSku.getSecKillId()),
                String.valueOf(cmsSecKillSku.getSpecId())));

        if (cmsSecKillSkuDto != null) {
            BeanUtil.copyProperties(cmsSecKillSku, cmsSecKillSkuDto, CopyOptions.create().setIgnoreNullValue(true));
            redisTemplate.opsForValue().set(RedisKeyUtil.getSecKillSkuKey(String.valueOf(cmsSecKillSku.getSecKillId()),
                    String.valueOf(cmsSecKillSku.getSpecId())), cmsSecKillSkuDto);
        }

        // 删除旧的图片文件
        if (ret > 0) {
            UploadFile uploadFile = new UploadFile();
            List<String> filePaths = new ArrayList<>();
            if (cmsSecKillSku.getOldPicUrl() != null && !"".equals(cmsSecKillSku.getOldPicUrl())) {
                filePaths.add(cmsSecKillSku.getOldPicUrl());
            }
            if (filePaths.size() > 0) {
                uploadFile.setFilePaths(filePaths);
                opcFileFeignApi.filesDelete(uploadFile);
            }
        }

        return ret;
    }

    @Override
    public void deleteById(Long id) {
        Boolean bDelete = true;

        // 判断该秒杀活动是否正在进行中，如果是则无法删除
        CmsSecKillSku cmsSecKillSku = findById(id);
        if (cmsSecKillSku == null) {
            Preconditions.checkState(bDelete, "没有该秒杀活动商品，无法删除");
        }

        bDelete = !cmsSecKillService.isSecKillOn(cmsSecKillSku.getSecKillId());
       // Preconditions.checkState(bDelete, "该秒杀活动正在进行中，无法删除");

        super.deleteById(id);

        // 删除缓存
        if (redisTemplate.hasKey(RedisKeyUtil.getSecKillSkuKey(String.valueOf(cmsSecKillSku.getSecKillId()),
                String.valueOf(cmsSecKillSku.getSpecId())))) {
            redisTemplate.delete(RedisKeyUtil.getSecKillSkuKey(String.valueOf(cmsSecKillSku.getSecKillId()),
                    String.valueOf(cmsSecKillSku.getSpecId())));//根据key删除缓存

            // 删除用户购买信息
            Set<String> keys = redisTemplate.keys(RedisKeyUtil.getSecKillSkuUserBuyPrexKey(String.valueOf(cmsSecKillSku.getSecKillId()),
                    String.valueOf(cmsSecKillSku.getSpecId())));
            if (CollectionUtils.isNotEmpty(keys)) {
                redisTemplate.delete(keys);
            }
        }

        // 删除图片文件
        UploadFile uploadFile = new UploadFile();
        List<String> filePaths = new ArrayList<>();
        if (cmsSecKillSku.getOldPicUrl() != null && !"".equals(cmsSecKillSku.getOldPicUrl())) {
            filePaths.add(cmsSecKillSku.getOldPicUrl());
        }
        if (filePaths.size() > 0) {
            uploadFile.setFilePaths(filePaths);
            opcFileFeignApi.filesDelete(uploadFile);
        }
    }

    @Override
    public void deleteByIdsExt(Long secKillId, String ids) {

        Boolean bSecKillOn = !cmsSecKillService.isSecKillOn(secKillId);
        //Preconditions.checkState(bSecKillOn, "要删除的秒杀商品所在的活动正在进行中，无法删除");

        List<CmsSecKillSku> cmsSecKillSkus = cmsSecKillSkuMapper.selectByIds(ids);
        super.deleteByIds(ids);

        List<Long> secKillIds = Arrays.asList(ids.split(",")).stream().map(id -> Long.valueOf(id)).collect(Collectors.toList());

        // 删除缓存商品
        for (Long id : secKillIds) {
            if (redisTemplate.hasKey(RedisKeyUtil.getSecKillSkuKey(String.valueOf(secKillId), String.valueOf(id)))) {
                redisTemplate.delete(RedisKeyUtil.getSecKillSkuKey(String.valueOf(secKillId), String.valueOf(id))); //根据key删除缓存
            }
        }

        // 删除图片
        UploadFile uploadFile = new UploadFile();
        List<String> filePaths = new ArrayList<>();
        for (CmsSecKillSku cmsSecKillSku : cmsSecKillSkus) {
            if (cmsSecKillSku.getPicUrl() != null)
                filePaths.add(cmsSecKillSku.getPicUrl());
        }
        uploadFile.setFilePaths(filePaths);
        opcFileFeignApi.filesDelete(uploadFile);
    }

    @Override
    public void updateStorageIncrement(Long secKillId, Long specId, Integer number, Integer lockNumber, Integer saledNumber) {
        // 更新DB
        cmsSecKillSkuMapper.updateStorageIncrement(secKillId, specId, number, lockNumber, saledNumber);

        // 更新缓存
        CmsSecKillSkuDto cmsSecKillSkuDto = (CmsSecKillSkuDto)redisTemplate.opsForValue().get(RedisKeyUtil.getSecKillSkuKey(String.valueOf(secKillId), String.valueOf(specId)));

        if (cmsSecKillSkuDto != null ) {
            cmsSecKillSkuDto.setLockCount(lockNumber);
            cmsSecKillSkuDto.setSaledCount(saledNumber);
            redisTemplate.opsForValue().set(RedisKeyUtil.getSecKillSkuKey(String.valueOf(secKillId), String.valueOf(specId)), cmsSecKillSkuDto);
        }
    }



}
